from xmlrpc.server import SimpleXMLRPCServer
import os
import task_util
import socket
import redis
from task_config import TASK_CONFIG

class TaskServer:
  def __init__(self, dir='./'):
    self.dir = dir

    all_files = []
    for root, dirs, files in os.walk(dir):
      for file in files:
        all_files.append(os.path.join(root, file))

    self.checksum = task_util.gen_checksums(all_files)

  def get_checksum(self):
    '''return checksum of all task files'''
    return self.checksum

  def get_all_file_stream(self):
    data = []
    for root, dirs, files in os.walk(self.dir):
      for f in files:
        fp = os.path.join(root, f)
        with open(fp, "rb") as fh:
          data.append((fp, fh.read()))
    return data

if __name__=='__main__':

  server_host = socket.gethostbyname(socket.gethostname())
  server_port = 8000

  redis_client = redis.Redis(host=TASK_CONFIG['redis_host'], port=TASK_CONFIG['redis_port'], db=TASK_CONFIG['redis_db'])
  redis_client.set('xmlrpc_host', server_host)
  redis_client.set('xmlrpc_port', server_port)

  server = SimpleXMLRPCServer((server_host, server_port))

  server.register_instance(TaskServer('scripts'))
  
  server.serve_forever()
